---
title: "Jackson Json Mixin"
date: 2020-03-04
categories:
- java
- jackson
tags:
---

<div id="content">
<p>
一般在类的字段上面加上 @JsonProperty 注解能构实现自定义的序列化逻辑。
但是如果是第三方的类，无法修改，想实现自定义序列化或反序列化，使用 @Mixin 
</p>
<p>
假如有一个 Feign API，被封闭到一个jar包里面了，不能更改
</p>
<div class="org-src-container">
<pre class="src src-java"><span style="font-weight: bold;">import</span> <span style="font-weight: bold; text-decoration: underline;">org</span>.<span style="font-weight: bold; text-decoration: underline;">springframework</span>.<span style="font-weight: bold; text-decoration: underline;">data</span>.<span style="font-weight: bold; text-decoration: underline;">domain</span>.<span style="font-weight: bold; text-decoration: underline;">Page</span>;

<span style="font-weight: bold;">interface</span> <span style="font-weight: bold; text-decoration: underline;">Client</span> {
    <span style="font-weight: bold; text-decoration: underline;">Page</span>&lt;<span style="font-weight: bold; text-decoration: underline;">DTO</span>&gt; <span style="font-weight: bold;">getList</span>(<span style="font-weight: bold; text-decoration: underline;">Pageable</span> <span style="font-weight: bold; font-style: italic;">pageable</span>);
}
</pre>
</div>
<p>
但这个 Page 是一个接口，无法被反序列化。
</p>
<p>
使用MixIn：
</p>
<div class="org-src-container">
<pre class="src src-java"><span style="font-weight: bold; text-decoration: underline;">@JsonDeserialize</span>(as = PageImpl.<span style="font-weight: bold;">class</span>)
    <span style="font-weight: bold;">private</span> <span style="font-weight: bold;">interface</span> <span style="font-weight: bold; text-decoration: underline;">PageMixIn</span> {
}

objectMapper.addMixIn(Page.<span style="font-weight: bold;">class</span>, PageMixIn.<span style="font-weight: bold;">class</span>);

</pre>
</div>
<p>
Page接口使用PageImpl类反序列化，这个PageImpl就是自己对Page接口的实现。
</p>
</div>
<div class="status" id="postamble">
<p class="date">Date: 2020-03-04</p>
<p class="author">Author: gdme1320</p>
<p class="validation"><a href="http://validator.w3.org/check?uri=referer">Validate</a></p>
</div>
